<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
import { invoke } from "@tauri-apps/api/core";
import { debug } from "@tauri-apps/plugin-log";

const route = useRoute();
const router = useRouter();

interface CreateMaterialRequest {
    name: string | null;
    code: string | null;
    parent_id: number;
    supplier_id: number | null;
    color_code: string | null;
    background_material: string | null;
    status: number;
    length: number | null;
    width: number | null;
    thickness: number | null;
    residual: number | null;
    price: number | null;
    unit: string | null;
    remark: string | null;
}

const form = ref<CreateMaterialRequest>({
    name: "",
    code: "",
    parent_id: 0,
    supplier_id: null,
    color_code: "",
    background_material: "",
    status: 1,
    length: null,
    width: null,
    thickness: null,
    residual: null,
    price: null,
    unit: "元",
    remark: null,
});

const loading = ref(false);
const error = ref("");
const success = ref("");

// 从查询参数获取父级ID
onMounted(() => {
    const parentId = route.query.parent_id;
    if (parentId) {
        form.value.parent_id = parseInt(parentId as string);
    }
});

async function submitForm() {
    if (!form.value.name?.trim()) {
        error.value = "材料名称不能为空";
        return;
    }

    loading.value = true;
    error.value = "";
    success.value = "";

    try {
        debug(`submitForm json: ${JSON.stringify(form.value)}`);
        const response = await invoke("create_material", {
            data: JSON.stringify(form.value),
        });

        success.value = "材料创建成功！";

        // 2秒后返回材料列表
        setTimeout(() => {
            router.back();
        }, 2000);
    } catch (err) {
        error.value = "创建材料失败：" + err;
        console.error("创建材料失败:", err);
    } finally {
        loading.value = false;
    }
}

function cancel() {
    router.back();
}

// 价格处理函数
const displayPrice = ref(0);

function setPrice(value: number) {
    form.value.price = Math.round(value * 10000);
}

function getDisplayPrice() {
    if (!form.value.price) return 0;
    return form.value.price / 10000;
}
</script>

<template>
    <main class="container mx-auto p-4 max-w-4xl">
        <h1 class="text-2xl font-bold mb-6">创建新材料</h1>

        <!-- 成功提示 -->
        <div v-if="success" class="alert alert-success mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M8.5 11.5 11 14l4-4m6 2a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ success }}</span>
        </div>

        <!-- 错误提示 -->
        <div v-if="error" class="alert alert-error mb-6">
            <svg
                class="w-6 h-6"
                aria-hidden="true"
                xmlns="http://www.w3.org/2000/svg"
                fill="none"
                viewBox="0 0 24 24"
            >
                <path
                    stroke="currentColor"
                    stroke-linecap="round"
                    stroke-linejoin="round"
                    stroke-width="2"
                    d="M12 13V8m0 8h0m9-4a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
                />
            </svg>
            <span>{{ error }}</span>
        </div>

        <div class="bg-base-100 rounded-lg shadow-sm border border-gray-200">
            <!-- 基本信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    基本信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >材料名称 *</span
                            >
                        </label>
                        <input
                            v-model="form.name"
                            type="text"
                            class="input input-bordered"
                            placeholder="请输入材料名称"
                            required
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">材料编码</span>
                        </label>
                        <input
                            v-model="form.code"
                            type="text"
                            class="input input-bordered"
                            placeholder="请输入材料编码"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >父级材料ID</span
                            >
                        </label>
                        <input
                            v-model="form.parent_id"
                            type="number"
                            class="input input-bordered"
                            disabled
                        />
                        <div class="text-xs text-gray-500 mt-1">
                            自动从上级页面获取
                        </div>
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">供应商ID</span>
                        </label>
                        <input
                            v-model="form.supplier_id"
                            type="number"
                            class="input input-bordered"
                            placeholder="请输入供应商ID"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">状态</span>
                        </label>
                        <select
                            v-model="form.status"
                            class="select select-bordered"
                        >
                            <option :value="1">启用</option>
                            <option :value="0">禁用</option>
                        </select>
                    </div>
                </div>
            </div>

            <!-- 尺寸及颜色 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    尺寸及颜色
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >长度（米）</span
                            >
                        </label>
                        <input
                            v-model="form.length"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="长度"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >宽度（米）</span
                            >
                        </label>
                        <input
                            v-model="form.width"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="宽度"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >厚度（毫米）</span
                            >
                        </label>
                        <input
                            v-model="form.thickness"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="厚度"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium"
                                >误差（毫米）</span
                            >
                        </label>
                        <input
                            v-model="form.residual"
                            type="number"
                            step="0.001"
                            class="input input-bordered"
                            placeholder="误差"
                        />
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">颜色代码</span>
                        </label>
                        <div class="flex gap-2">
                            <input
                                v-model="form.color_code"
                                class="input input-bordered flex-1"
                                placeholder="颜色代码"
                            />
                            <div
                                v-if="form.color_code"
                                class="w-10 h-10 rounded border border-gray-300"
                                :style="{ backgroundColor: form.color_code }"
                            ></div>
                        </div>
                    </div>

                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">背面材料</span>
                        </label>
                        <input
                            v-model="form.background_material"
                            class="input input-bordered"
                            placeholder="背面材料"
                        />
                    </div>
                </div>
            </div>

            <!-- 价格信息 -->
            <div class="p-6 border-b border-gray-200">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    价格信息
                </h3>
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div class="form-control">
                        <label class="label">
                            <span class="label-text font-medium">价格</span>
                        </label>
                        <div class="flex gap-2">
                            <input
                                :value="getDisplayPrice()"
                                @input="
                                    setPrice(
                                        parseFloat(
                                            ($event.target as HTMLInputElement)
                                                .value,
                                        ) || 0,
                                    )
                                "
                                type="number"
                                step="0.01"
                                class="input input-bordered flex-1"
                                placeholder="价格"
                            />
                            <select
                                v-model="form.unit"
                                class="select select-bordered w-28"
                            >
                                <option value="元">元</option>
                                <option value="美元">美元</option>
                                <option value="欧元">欧元</option>
                                <option value="英镑">英镑</option>
                                <option value="日元">日元</option>
                            </select>
                        </div>
                        <div class="text-xs text-gray-500 mt-1">
                            存储值: {{ form.price }} (显示值 × 10000)
                        </div>
                    </div>
                </div>
            </div>

            <!-- 备注信息 -->
            <div class="p-6">
                <h3 class="text-lg font-semibold text-gray-800 mb-4">
                    备注信息
                </h3>
                <div class="form-control">
                    <textarea
                        v-model="form.remark"
                        class="textarea textarea-bordered h-24"
                        placeholder="请输入备注信息"
                    ></textarea>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="flex justify-end gap-3 mt-6">
            <button
                type="button"
                @click="cancel"
                class="btn btn-outline"
                :disabled="loading"
            >
                取消
            </button>
            <button
                type="button"
                @click="submitForm"
                class="btn btn-primary"
                :disabled="loading"
            >
                <span
                    v-if="loading"
                    class="loading loading-spinner loading-sm"
                ></span>
                创建材料
            </button>
        </div>
    </main>
</template>

<style scoped>
.form-control {
    display: flex;
    flex-direction: column;
}

.label {
    padding: 0;
    margin-bottom: 0.5rem;
}

.label-text {
    font-weight: 500;
    color: #374151;
}
</style>
